from django.http import JsonResponse
from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework_simplejwt.exceptions import InvalidToken, TokenError
from django.middleware.csrf import CsrfViewMiddleware
import re
from django.conf import settings


class JWTAuthenticationMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        if 'api' in request.path:  # 只处理 API 请求
            auth_header = request.headers.get('Authorization')
            if auth_header:
                try:
                    # 分离 Bearer 和 token
                    auth_parts = auth_header.split()
                    if len(auth_parts) == 2 and auth_parts[0].lower() == 'bearer':
                        jwt_auth = JWTAuthentication()
                        validated_token = jwt_auth.get_validated_token(auth_parts[1])
                        request.user = jwt_auth.get_user(validated_token)
                except (InvalidToken, TokenError) as e:
                    return JsonResponse({
                        'detail': str(e)
                    }, status=401)

        response = self.get_response(request)
        return response


class CustomCsrfMiddleware(CsrfViewMiddleware):
    def process_view(self, request, callback, callback_args, callback_kwargs):
        # 检查请求路径是否在豁免列表中
        path = request.path_info.lstrip('/')
        for exempt_pattern in getattr(settings, 'CSRF_EXEMPT_URLS', []):
            if re.match(exempt_pattern, path):
                return None
        return super().process_view(request, callback, callback_args, callback_kwargs)